<?php
require 'vendor/autoload.php';
use QL\QueryList;
use GuzzleHttp\Cookie\CookieJar;


function getCustomerMoney($phone, $beginTime, $endTime)
{
    $time_data = file_get_contents('./time.txt');
    if ((time() - $time_data) > 600) {
        login();
    } else {
        file_put_contents('./time.txt', time());
    }

    // die(var_dump(time() - $time_data));
    $cookieArr = file_get_contents('./cookie.txt');
    $cookieArr = json_decode($cookieArr, true);
    $jar = new CookieJar(false, $cookieArr);
    $cookieArr2 = file_get_contents('./cookie.txt');
    $cookieArr2 = json_decode($cookieArr2, true);
    $jar2 = new CookieJar(false, $cookieArr2);

    // $phone = $_POST['phone'];
    // $beginTime = $_POST['beginTime'];
    // $endTime = $_POST['endTime'];

    $ql2 = QueryList::post('https://beta42.pospal.cn/Customer/LoadCustomerMoneyChangeLogs', [
        "customerNumber" => $phone,
        "beginTime" => $beginTime,
        "endTime" => $endTime,

    ], [
        'cookies' => $jar2
    ]);
    $data = json_decode($ql2->getHtml(false), true);
    // die(var_dump($ql2->getHtml(false)));
    if (empty($data['mainTableView'])) {
        echo json_encode(['code' => 1, 'msg' => '没有数据', 'data' => []]);
        exit;
    } else {
        $html = json_decode($ql2->getHtml(false), true)['mainTableView'];
        $table = QueryList::html($html);
        $tableRows = $table->find('tr:gt(0)')->map(function ($row) {

            $data = $row->find('td')->texts()->all();
            $val['date'] = $data[0];
            $val['b'] = $data[1];
            $val['type'] = $data[2];
            $val['d'] = $data[3];
            $val['balance'] = $data[4];
            $f = (string) $data[5];
            if (strpos($f, '充值') === 0) {
                $val['f'] = $f;
            } else {
                $val['f'] = substr($f, 18, 21);
            };

            return $val;
            // die (var_dump($val));
            // $keys = ['date', 'b', 'type', 'd', 'balance', 'f'];
            // return array_combine($keys, $row->find('td')->texts()->all());
        });
    }
    return $tableRows;
}





function login()
{
    $jar = new CookieJar();
    $ql = QueryList::post('https://beta42.pospal.cn/account/signin', [
        'username' => 'ld18279969699',
        'password' => 'ld8302361',
    ], [
        'cookies' => $jar
    ]);

    $cookieArr = $jar->toArray();
    file_put_contents('./cookie.txt', json_encode($cookieArr));
    file_put_contents('./time.txt', time());

}